package com.scud.system.service.impl;

import cn.hutool.core.util.StrUtil;
import com.scud.common.constants.RedisConstants;
import com.scud.common.error.ErrorConstants;
import com.scud.common.exception.ScudException;
import com.scud.common.regex.RegexPatterns;
import com.scud.model.system.dto.LoginDto;
import com.scud.model.system.pojo.User;
import com.scud.system.mapper.UserMapper;
import com.scud.system.service.AuthService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Objects;

@Service("code_auth")
public class CodeAuthServiceImpl implements AuthService {
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private UserMapper userMapper;
    @Override
    public User execute(LoginDto loginDto) {
        String phone = loginDto.getPhone();
        String code = loginDto.getCode();
        //校验手机号
        if (StrUtil.isBlank(phone) || !phone.matches(RegexPatterns.PHONE_REGEX)) {
            throw new ScudException(ErrorConstants.PHONE_ILL_LEGAL);
        }
        //手机号没有对应的验证码
        if (Boolean.FALSE.equals(stringRedisTemplate.hasKey(RedisConstants.CODE + phone))){
            throw new ScudException(ErrorConstants.PHONE_ILL_LEGAL);
        }
        String codeDb = stringRedisTemplate.opsForValue().get(RedisConstants.CODE + phone);
        //验证码不合法
        if (StrUtil.isBlank(code)||!code.equals(codeDb)){
            throw new ScudException(ErrorConstants.CODE_ILL_LEGAL);
        }
        User user = userMapper.getUserByPhone(phone);
        if (Objects.isNull(user)){
            //用户不存在，直接注册
            user = User.builder().phone(phone).status(1).build();
            userMapper.insertUser(user);
        }
        return user;
    }
}
